﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using Intelligent.OTC.Domain.DataModel;
using Intelligent.OTC.Common.UnitOfWork;
using Intelligent.OTC.Domain;
using Intelligent.OTC.Business;
using Intelligent.OTC.Domain.Repositories;
using Intelligent.OTC.Common;
using System.Configuration;
using System.IO;
using Intelligent.OTC.Common.Utils;
using Intelligent.OTC.WebApi.Core;
using Intelligent.OTC.Common.Exceptions;


using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using Intelligent.OTC.Common.Attr;

namespace Intelligent.OTC.WebApi.Controllers
{
    [UserAuthorizeFilter(actionSet: "dataprepare")]
    public class CollectionController : ApiController
    {
        public const string strArchiveAccountKey = "ArchiveAccountLevelPath";//ArchiveAccount路径的config保存名
        public const string strArchiveInvoiceKey = "ArchiveInvoiceLevelPath";//ArchiveInvoice路径的config保存名
        public const string strArchiveOneYearSalesKey = "ArchiveOneYearSalesPath";//ArchiveOneYearSales路径的config保存名

        [HttpGet]
        [PagingQueryable]
        public IEnumerable<CustomerAging> Get()
        {
            ICustomerService service = SpringFactory.GetObjectImpl<ICustomerService>("CustomerService");
            return service.GetCustomerAging();
        }

        [HttpPost]
        public String UploadFile(string levelFlag)
        {
            lock (strArchiveAccountKey)
            {
                // perform save file to local path
                HttpFileCollection files = HttpContext.Current.Request.Files;
                string msg = string.Empty;
                string archivePath = string.Empty;
                string archiveFileName = string.Empty;
                string archiveZIPFileName = string.Empty;
                FileType fileT = FileType.Account;
                FileUploadHistory accFileName = new FileUploadHistory();
                FileUploadHistory invFileName = new FileUploadHistory();
                string strCode;
                string strMessage = string.Empty;
                FileService service = SpringFactory.GetObjectImpl<FileService>("FileService");
                bool isSaved = false;
                try
                {
                    if (files.Count > 0)
                    {
                        CustomerService custService = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");

                        if (levelFlag == "0")
                        {
                            fileT = FileType.Account;
                            archivePath = ConfigurationManager.AppSettings[strArchiveAccountKey].ToString();
                        }
                        else if (levelFlag == "1")
                        {
                            fileT = FileType.Invoice;
                            archivePath = ConfigurationManager.AppSettings[strArchiveInvoiceKey].ToString();
                        }
                        else if (levelFlag == "2")
                        {
                            fileT = FileType.OneYearSales;
                            archivePath = ConfigurationManager.AppSettings[strArchiveOneYearSalesKey].ToString();
                        }

                        archivePath = archivePath + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.Month.ToString();

                        if (Directory.Exists(archivePath) == false)
                        {
                            Directory.CreateDirectory(archivePath);
                        }


                        if (levelFlag == "2")
                        {
                            archiveFileName = archivePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + fileT.ToString() +
                                    "-" + AppContext.Current.User.EID + "-" + DateTime.Now.ToString("HHmmssf") + ".xlsx";
                        }
                        else
                        {
                            archiveFileName = archivePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + fileT.ToString() +
                                    "-" + AppContext.Current.User.EID + "-" + DateTime.Now.ToString("HHmmssf") + ".txt";
                        }

                        //if (files[0].ContentType == "application/zip")
                        if (files[0].FileName.ToUpper().Split('.')[1] == "ZIP")
                        {
                            archiveZIPFileName = archivePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + fileT.ToString() +
                                    "-" + AppContext.Current.User.EID + "-" + DateTime.Now.ToString("HHmmssf") + ".zip";
                            files[0].SaveAs(archiveZIPFileName);
                            unZip(archiveZIPFileName, archiveFileName);
                            isSaved = true;
                        }
                        service.UploadFile(files[0], archiveFileName, fileT, true, isSaved);

                        ICustomerService cusService = SpringFactory.GetObjectImpl<ICustomerService>("CustomerService");

                        strCode = Helper.EnumToCode<FileType>(FileType.Account);
                        accFileName = service.GetNewestData(strCode);
                        strCode = Helper.EnumToCode<FileType>(FileType.Invoice);
                        invFileName = service.GetNewestData(strCode);
                        if (accFileName != null && invFileName != null)
                        {
                            // account file和invoice file同时上传
                            Helper.Log.Info("Aging file Upload finished! Dataimport Start!");
                            cusService.allFileImport();
                            strMessage = "Account And Invoice File Upload Successful!";
                        }

                        if (levelFlag == "2")
                        {
                            // One-Year Sales file 上传
                            Helper.Log.Info("One-Year Sales file Upload finished! Dataimport Start!");
                            cusService.uploadOneYearSales();
                            strMessage = "One-Year Sales File Upload Successful!";
                        }

                    }

                    return strMessage;
                }
                catch (AgingImportException ex)
                {
                    Helper.Log.Error(ex.Message, ex);
                    //将DB中的未处理状态变成cancel状态
                    service.UpdateAllProcessFlagCancel();
                    throw new OTCServiceException(ex.Message);
                }
                catch (Exception ex)
                {
                    Helper.Log.Error(ex.Message, ex);
                    //将DB中的未处理状态变成cancel状态
                    service.UpdateAllProcessFlagCancel();
                    throw new OTCServiceException("Uploaded file error!");
                }
            }
        }


        public void unZip(string zipfile, string archiveFileName)
        {
            if (!File.Exists(zipfile))
            {
                Helper.Log.Error(string.Format("Cannot find file '{0}'", zipfile), null);
                return;
            }
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipfile)))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {

                    Helper.Log.Info(theEntry.Name);

                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    // create directory
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(archiveFileName))
                        {

                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        [HttpPost]
        public void Submit([FromBody]List<string> agingIds)
        {

            //CustomerService custService = SpringFactory.GetObjectImpl<CustomerService>("CustomerService");
            //custService.SubmitInitialAging(agingIds);

        }

    }
}